import logging

from flask import request

from global_config import app_id, app_secret
from utils.decorators.request_limit import request_limit
from utils.exceptions import custom_abort
from utils.session import session
from . import api


@api.route("/getopenid", methods=["GET"])
@request_limit(666)
def handle_exam():
    code = request.args.get('code', '')
    post_data = {
        'appid': app_id,
        'secret': app_secret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    try:
        res = session.post(url="https://api.weixin.qq.com/sns/jscode2session", data=post_data).json()
        logging.info("新用户!openid为:"+res['openid'])
        return {
            'code': 0,
            'data': {
                'openId': res['openid']
            },
        }
    except Exception:
        logging.error("获取openid异常!")
        custom_abort(-1)



